<template>
  <CDialog
    :visible="visible"
    title="关联电站"
    type="add"
    width="1200px"
    @submit="handleSubmit"
    @cancel="handleCancel"
  >
    <div v-loading="tableLoading">
      <TableSearch
        ref="tableSearch"
        :pageNameDisplay="false"
        :tableBtns="tableBtns"
        :columns="columns"
        :tableData="tableData"
        :form="tableForm"
        @handleTableData="handleTableData"
      >
        <template slot="tableSearchHeader">
          <div class="advert-detail-table__header">
            <div class="advert-detial-table__header__title">选择投保电站</div>
            <div
              @click="handleClearCheckList"
              class="advert-detial-table__header__button"
            >
              清空选择电站
            </div>
            <!-- <div
              @click="handlePreview"
              class="advert-detial-table__header__button"
            >
              预览所选电站
              <span class="dvert-detial-table__header__button_red">{{
                `(已选择电站：${this.checkList.length}个)`
              }}</span>
            </div> -->
          </div>
          <div class="search-form">
            <i-form :default-span="20" :model="tableForm" :label-width="130">
              <el-form-item label="选择投保电站：">
                <el-col style="line-height: 32px" :span="130">
                  <div>
                    <el-input
                      v-model="tableForm.stationName"
                      placeholder="请输入电站名称"
                    ></el-input>
                  </div>
                </el-col>
              </el-form-item>
              <el-form-item class="is-required" label="选择投保方案：">
                <el-col style="line-height: 32px" :span="130">
                  <div>
                    <el-radio-group v-model="tableForm.resource">
                      <el-radio :label="1001">按照端口投保</el-radio>
                      <el-radio :label="1002">按照电站投保</el-radio>
                    </el-radio-group>
                  </div>
                </el-col>
              </el-form-item>
            </i-form>
            <el-button type="success" @click="handleQuery">查询</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
            <el-button type="primary" @click="handleCheckAll"
              >结果全选</el-button
            >
          </div>
        </template>
        <el-table-column slot="checkbox" label="选择电站">
          <template #default="{ row }">
            <el-checkbox
              :key="row.id + resetKey"
              @change="
                (val) => {
                  handleCheckChange(val, row)
                }
              "
              :checked="checkList.includes(row.id)"
            />
          </template>
        </el-table-column>
      </TableSearch>
    </div>
    <PreviewStationDlgInsurance
      :visible.sync="previewVisible"
      v-if="previewVisible"
      :check-list="checkList"
    />
  </CDialog>
</template>
<script>
import CDialog from '@/components/CDialog'
import TableSearch from '@/components/TableSearch'
import PreviewStationDlgInsurance from '../../activity/components/PreviewStationDlgInsurance'
import formatter from '@/utils/format'
import { nationsLinkStationPage, insuranceAdd } from '@/api/Insurance'

export default {
  name: 'InsuranceSetAdd',
  components: { CDialog, TableSearch, PreviewStationDlgInsurance },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      tableLoading: false,
      previewVisible: false,
      resetKey: 1,
      tableBtns: [],
      tableData: {},
      tableForm: { resource: '', stationName: '' },
      columns: [
        {
          slot: 'checkbox',
        },
        {
          label: '创建日期',
          prop: 'createTime',
          formatter,
          resourceId: '/web/station-insurance/manager/投保方案',
        },
        {
          label: '所在地区',
          prop: 'provinceName',
          formatter: (row) => {
            return `${
              row.provinceName
                ? row.provinceName +
                  ' - ' +
                  row.cityName +
                  ' - ' +
                  row.districtName
                : ''
            }`
          },
        },
        {
          label: '充电站名',
          prop: 'stationName',
        },
        {
          label: '地址描述',
          prop: 'stationAddress',
        },
        {
          label: '停用状态',
          prop: 'unableCyclesStatusDesc',
        },
        {
          label: '包含充电口',
          prop: 'plug',
        },
      ],
      checkList: [],
    }
  },
  methods: {
    handleCheckAll() {
      this.tableLoading = true
      nationsLinkStationPage({
        ...this.selectAllResultForm,
        pageSize: 50,
        currentPage: 1,
      })
        .then((res) => {
          if (!res.totalAmount) throw Error('no totalAmount')
          this.checkList = []

          this.recurrence(res.totalAmount, 1, 50)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    recurrence(totalAmount, currentPage, pageSize) {
      nationsLinkStationPage({
        ...this.selectAllResultForm,
        pageSize,
        currentPage,
      })
        .then((res) => {
          if (!Array.isArray(res.list)) throw Error('no valid res.list')

          res.list.forEach((item) => {
            this.checkList.push(item.id)
          })

          if (currentPage * pageSize < totalAmount + pageSize) {
            this.recurrence(totalAmount, currentPage + 1, pageSize)
          } else {
            this.tableLoading = false
            this.resetKey += 1
          }
        })
        .catch((err) => {
          console.log(err)
          this.tableLoading = false
        })
    },
    handleQuery() {
      this.$refs.tableSearch.handleTableData()
    },
    reset() {
      this.tableForm = {}
      this.$nextTick(() => {
        this.$refs.tableSearch.handleTableData()
      })
    },

    handleCheckChange(val, row) {
      if (val && !this.checkList.includes(row.id)) {
        this.checkList.push(row.id)
      }
      if (!val && this.checkList.includes(row.id)) {
        let index = this.checkList.findIndex((item) => item == row.id)
        this.checkList.splice(index, 1)
      }
    },
    handlePreview() {
      if (this.checkList.length <= 0) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '选择电站之后才可预览！',
        })
        return
      }
      this.previewVisible = true
    },
    handleClearCheckList() {
      this.checkList = []
      this.resetKey += 1
    },
    handleSubmit() {
      console.log('添加', this.tableForm.resource, this.checkList)
      if (!this.tableForm.resource) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '请选择投保方案',
        })
        return
      }

      if (this.checkList.length == 0) {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '请选择投保电站',
        })
        return
      }

      this.tableLoading = true

      insuranceAdd({
        schemeType: this.tableForm.resource == 1001 ? 'PORT' : 'STATION',
        stationIds: this.checkList.join(','),
      })
        .then((res) => {
          console.log(res)
          this.$emit('update:visible', false)
          this.refresh()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    refresh() {
      this.$emit('refresh')
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    handleTableData(params) {
      this.tableLoading = true
      nationsLinkStationPage(params)
        .then((res) => {
          this.tableData = {
            list: res.list,
            totalCount: res.totalAmount,
          }
          this.selectAllResultForm = params
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.advert-form {
  padding-right: 300px;
}

.search-form {
  padding-top: 20px;
  display: flex;

  .el-button {
    height: 40px;
    margin-left: 20px;
  }
}

.advert-detail-table__header {
  padding-left: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  flex-wrap: wrap;
}

.advert-detial-table__header__title {
  font-size: 14px;
  font-weight: bold;
  padding-right: 150px;
}

.advert-detial-table__header__button {
  cursor: pointer;
  font-size: 14px;
  color: #4075fe;
  cursor: pointer;
  margin-right: 40px;

  .dvert-detial-table__header__button_red {
    color: red;
  }
}
</style>
